<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".__("Member Chip Withdrawal");
$page_title=__("Member Chip Withdrawal");

if(!$pv["task"]["Withdrawal"]){
	$errmsg="<h2>$page_title</h2>".format_err(__("You do not have the privilege to manage member withdrawal."));

	print format_admin_page($errmsg, $this_title);
	exit();
}

$add_edit_file='cwithdraw_ae.php';

$item_per_page=$vars['admin_item_per_page'];
$search_options["status"]["option"] = $r_status = array("pending","paid","cancelled");
$search_options["status"]["option_display"] = $r_status_d = array("pending"=>__("Pending Payment"),"paid"=>__("Paid"),"cancelled"=>__("Cancelled"));
$search_options["status"]["display"] = __("Status");
$search_options["payment_type"]["option"] = $r_payment = array("c","d","e","o");
$search_options["payment_type"]["option_display"] = $r_payment_d = array("c"=>__("Cash"), "d"=>__("Cheque"), "e"=>__("Credit Card"), "o"=>__("On-hold"));
$search_options["payment_type"]["display"] = __("Payment Type");

//#####AJAX CALL#####
if($_GET["aj"] && $_GET["check_con"]){
	exit();
}
//#####END AJAX CALL#####

//#####UPDATE WITHDRAWAL POST#####
if($_POST["__req"]){
	$settings=get_settings("member_wit_sec_pass");
	if(!strlen($post_s["sec_pass"])){
		$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Security Password")))."<br />\n";
	}else{
		if($post_s['sec_pass'] != $settings['member_wit_sec_pass']){
			$errmsg.=__("You have entered an invalid Security Password.")."<br />\n";
		}
	}
	if(!$errmsg){
		$pr_dbr=explode("#", $vars["dbr"]["member_withdraw"]["payment_remark"]);
		foreach($post_s as $f => $v){
			if(preg_match('/^_cpay_[0-9]+$/', $f) && $v){
				$wid=preg_replace('/^_cpay_/', '', $f);
				$checkid[]=$wid;
				$r=mysql_query("select * from $db->member_withdraw where id='$wid' limit 1");
				if(!@mysql_num_rows($r)){
					$ne_errmsg.=replace_tag(__("Withdrawal ID: <%id%> does not exist."), array("<%id%>"=>strval($wid)))."<br />\n";
				}elseif(($wit_status=mysql_result($r, 0, "status"))!="pending"){
					$np_errmsg.=replace_tag(__("Withdrawal ID: <%id%> Status: <%status%>."), array("<%id%>"=>strval($wid), "<%status%>"=>$r_status_d[$wit_status]))."<br />\n";
				}
				if(!strlen($post_s["payment_date_$wid"])){
					$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>replace_tag(__("Payment Date for Withdrawal ID: <%id%>"), array("<%id%>"=>strval($wid)))))."<br />\n";
				}elseif(!verify_date($post_s["payment_date_$wid"])){
					$errmsg.=replace_tag(__("'<%field%>' is not a valid date format, enter YYYY-MM-DD only."), array("<%field%>"=>replace_tag(__("Payment Date for Withdrawal ID: <%id%>"), array("<%id%>"=>strval($wid)))))."<br />\n";
				}
				if(!strlen($post_s["payment_remark_$wid"])){
					$errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>replace_tag(__("Payment Remark for Withdrawal ID: <%id%>"), array("<%id%>"=>strval($wid)))))."<br />\n";
				}elseif(strlen($post_s["payment_remark_$wid"]) > $pr_dbr[2]){
					$errmsg.=replace_tag(__("'<%field%>' must between <%min%> to <%max%> characters only. You have entered <%no%> character(s)."), array("<%field%>"=>replace_tag(__("Payment Remark for Withdrawal ID: <%id%>"), array("<%id%>"=>strval($wid))), "<%min%>"=>"1", "<%max%>"=>strval($pr_dbr[2]), "<%no%>"=>strval(strlen($post_s["payment_remark_$wid"]))))."<br />\n";
				}
			}
		}
		if($ne_errmsg){
			$errmsg=__("Some of the withdrawal record(s) does not exist:")."<br />\n<br />\n$ne_errmsg<br />\n";
		}
		if($np_errmsg){
			$errmsg=replace_tag(__("Some of the withdrawal record(s) is not '<%status%>':"), array("<%status%>"=>$r_status_d["pending"]))."<br />\n<br />\n$np_errmsg<br />\n".replace_tag(__("It will be removed from the <%status%> list below."), array("<%status%>"=>$r_status_d["pending"]))."<br />\n";
		}
	}

	if(!$errmsg && count($checkid)){
		$datetime=ndate($vars["system_date_format"]);
		$wfi=$wsi=0;
		foreach($checkid as $id){
			$wit_uid=mysql_result(mysql_query("select uid from $db->member_withdraw where id='$id'"), 0);
			if(!mysql_query($sql="update $db->member_withdraw set payment_type='d', payment_date='".$post_d["payment_date_$id"]."', payment_remark='".$post_d["payment_remark_$id"]."', status='paid' where id='$id'")){
				$uf_errmsg.=replace_tag(__("Withdrawal ID: <%id%>."), array("<%id%>"=>strval($id)))."<br />\n";
				$uf_wit[$wfi]["id"]=$id;
				$uf_wit[$wfi]["uid"]=$wit_uid;
				$uf_wit[$wfi]["msg"]=replace_tag(__("Withdrawal ID: <%id%>."), array("<%id%>"=>strval($id)))."<br />\n";
				$wi++;
			}else{
				$us_msg.=replace_tag(__("Withdrawal ID: <%id%>."), array("<%id%>"=>strval($id)))."<br />\n";
				$us_wit[$wsi]['id'] = $id;
				$us_wit[$wsi]['uid'] = $wit_uid;
				$wsi++;
			}
		}
		if($us_msg){
			$msg=__("The withdrawal record(s) below has been successfully updated:")."<br />\n<br />\n$us_msg<br />\n";
		}
		if($uf_errmsg){
			$errmsg=($msg? $msg."<br />\n".__("However there was error updating some records.")." " : "").__("The withdrawal record(s) below cannot be updated:")."<br />\n<br />\n$uf_errmsg<br />\n";
			$critical_error=$errmsg;
		}
	}

	//log critical error
	$log_code="a-mwb";
	if($critical_error || $uf_wit){
		if($uf_wit){
			foreach($uf_wit as $index => $wit_err){
				$affected_uid=$wit_err["uid"];
				//log_activity('e', 'a', $aid, 'u', $affected_uid, $log_code, "Withdrawal update error: ".$wit_err["msg"], array("wid"=>$wit_err['id']));
			}
		}
		if($critical_error){
			//log_activity('e', 'a', $aid, 'u', 0, $log_code, $critical_error);
		}
	}
	if($us_wit){
		foreach($us_wit as $index => $details){
			$affected_uid = $details['uid'];
			//log_activity('a', 'a', $aid, 'u', $affected_uid, $log_code, "Withdrawal bulk updated", array("wid"=>$details['id']));
		}
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err($errmsg) : "";
}
//#####END UPDATE WITHDRAWAL POST#####

//#####SEARCH POST#####
if($_GET["s"]){
	$searching=1;
	$search_query=wit_search($get_d);
}
//textbox search, prefix "_sp_"
$r_textsearch=array("id"=>__("Withdraw ID"),"uid"=>__("Member ID"),"acc_name"=>__("Bank"),"acc_payee_name"=>__("Payee Name"),"acc_no"=>__("Acc. No."));

$searchfields_ordering=array("id","uid","acc_no","status","payment_type");
$search_ui=build_admin_search_ui($searching, $this_file, $search_options, $r_textsearch, $searchfields_ordering, $inputbox_style);
//#####END SEARCH POST#####

//#####LIST WITHDRAWAL#####
unset($dis);
if($_GET["_q"]=="pending" && $_POST["__req"]){
	foreach($post_s as $f=>$v){
		if(preg_match('/^_cpay_[0-9]+$/', $f) || preg_match('/^payment_date_[0-9]+$/', $f) || preg_match('/^payment_remark_[0-9]+$/', $f)){
			$dis[$f]=$post_h[$f];
		}
	}
}

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=jquery.js'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 init_checkall();".

 #check all click/change
 "
 j('input#cpall').click(function(){
  update_checkall();
 });
 j('input#cpall').change(function(){
  update_checkall();
 });".

 #single uncheck -> uncheck the checkall checkbox
 "
 j('input[@name^=_cpay_]').click(function(){
  init_checkall();    
 });
 j('input[@name^=_cpay_]').change(function(){
  init_checkall();    
 });".

 #payment date / remark keypress check the checkbox
 "
 j('input[@name^=payment_date_], input[@name^=payment_remark_]').keyup(function(){
  if(j(this).attr('name').match('payment_date_')){
   var id=j(this).attr('name').replace(/payment_date_/, '');
  }else{
   var id=j(this).attr('name').replace(/payment_remark_/, '');
  }
  if(j('input[@name=payment_date_'+id+']').val()=='' && j('input[@name=payment_remark_'+id+']').val()==''){
   j('input[@name=_cpay_'+id+']').attr('checked','');
  }else{
   j('input[@name=_cpay_'+id+']').attr('checked','checked');
  }
 });".

 #submit
 "
 j('input#btn_sb').click(function(){
  if(confirm('".addslashes(__("Convert the selected pending withdraw list into 'Paid' with payment type being 'Cheque'."))."\\n\\n".addslashes(__("Are you sure?"))."')){
	  j('input#btn_sb').attr('disabled','disabled');
	  j('div#msg_box').html('');
	  j.ajax({
	   url:'$this_file?aj=1&check_con=1',
	   dataType: 'html',
	   error: function(){
		j('div#msg_box').html('".AddSlashes(__("Opps.. some error occur, it seems there is no connection. Please try again."))."').addClass('red');
		j('input#btn_sb').attr('disabled','');
	   },
	   success: function(data){
		var mesg='';
		if(j('loggedout', data).text()=='loggedout'){
		 mesg='".AddSlashes(__("You have been logged out."))." ".AddSlashes(replace_tag(__("Please <%link%>re-login<%/link%> (a new window will open so you won't lose your work)."), array("<%link%>"=>"<a href='index.php' target='_blank'>", "<%/link%>"=>"</a>")))."';
		 j('div#msg_box').html(mesg).addClass('red');
		 j('input#btn_sb').attr('disabled','');
		}else{
		 j('form[@name=payment_form]').submit();
		}
	   }
	  });
  }
  return false;
 });

 function update_checkall(){
  var checked=j('input#cpall').attr('checked');
  j('input[@name^=_cpay_]').each(function(){
   j(this).attr('checked', checked? 'checked' : '');
  });
 }

 function init_checkall(){
  var keep_search=true;
  j('input[@name^=_cpay_]').each(function(){
   if(keep_search && !j(this).attr('checked')){
    keep_search=false;
   }
  });
  if(keep_search){
   j('input#cpall').attr('checked','checked');
  }else{
   j('input#cpall').attr('checked','');
  }
 }
});
</script>";

if($searching){
	$count_sql=$search_query["count_sql"];
	$record_sql=$search_query["record_sql"];
}else{
	if($_GET["_q"]=="pending"){
		$count_sql="select count(*) from $db->member_withdraw where status='pending'";
		$record_sql="select * from $db->member_withdraw where status='pending' order by id";
	}else{
		$count_sql="select count(*) from $db->member_withdraw";
		$record_sql="select * from $db->member_withdraw order by id limit <%limit_start%>, <%limit%>";
	}
}

$cur_page=$_GET["nav"];
$total_record=@mysql_result(mysql_query($count_sql), 0);
if($_GET["_q"]=="pending"){
	$this_page_total=@mysql_num_rows($r=mysql_query($record_sql));
}else{
	$total_page=ceil($total_record/$item_per_page);
	$page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
	$limit_start=($page-1)*$item_per_page;
	$nav_link=format_page_admin($page, $total_page, $this_file);
	$this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
}
$k=0;
for($i=0;$i<$this_page_total;$i++){
	$wit=mysql_fetch_assoc($r);
	if($wit["uid"] && !$r_user[$wit["uid"]]){
		$r_user[$wit["uid"]]=get_user_detail_by_id($wit['uid']);
	}
	$edit_link="<a href=\"$add_edit_file?type=edit&id=$wit[id]\"><img src='".M_URL."/images/icons/edit.png'></a>";
	$wit_row.="
	<tr class='row$k'>
		<td>$edit_link</td>".($_GET["_q"]=="pending"? "
		<td><input type='checkbox' name='_cpay_$wit[id]' ".($dis["_cpay_$wit[id]"]? "checked='checked'" : "")." id='cp_$wit[id]' /></td>" : "")."
		<td>$wit[id]</td>
		<td>".__("ID").__(":")." $wit[uid] ".__("(").$r_user[$wit["uid"]]["name"].__(")")."</td>
		<td>".number_format($wit["amount"], 2)."</td>
		<td>".$r_payment_d[$wit["payment_type"]]."</td>
		<td>$wit[acc_name]</td>
		<td>$wit[acc_payee_name]</td>
		<td>$wit[acc_no]</td>
		<td>".($_GET["_q"]=="pending"? "<input type='text' name='payment_date_$wit[id]' value=\"".$dis["payment_date_$wit[id]"]."\" style='width:120px;' />" :
			($wit["payment_date"]=="0000-00-00 00:00:00"? "-" : date($vars["date_format"], strtotime($wit["payment_date"]))))."</td>
		<td>".($_GET["_q"]=="pending"? "<input type='text' name='payment_remark_$wit[id]' value=\"".$dis["payment_remark_$wit[id]"]."\" style='width:120px;' />" : "$wit[payment_remark]")."</td>
		<td>$wit[remark]</td>
		<td>".$r_status_d[$wit["status"]]."</td>
		<td>".date($vars["date_format_short"], strtotime($wit["cdate"]))."</td>
	</tr>";
	$k=1-$k;
}

//listing text
$listing_text=replace_tag($searching? __("Search returned <%x%> <%listing%>") : ($_GET["_q"]=="pending"? __("Listing <%x%> Pending Payment <%listing%>") : __("Listing <%x%> <%listing%>")), array("<%x%>"=>strval($total_record), "<%listing%>"=>$total_record>1? __("Member Withdrawal") : __("Member Withdrawals"))).__(".").($searching? " ".replace_tag(__("<%link%>Clear Search and Refresh<%/link%>."), array("<%link%>"=>"<a href='$this_file'>", "<%/link%>"=>"</a>")) : "").($_GET["_q"]=="pending"? " ".replace_tag(__("<%link%>Show All<%/link%>."), array("<%link%>"=>"<a href='$this_file'>", "<%/link%>"=>"</a>")) : "");

//listing
$wit_list=($msg || $errmsg ? $msg.$errmsg : "").
"<input type='button' value='".__("Add Withdrawal")."' onclick=\"window.location='$add_edit_file?type=add';\" />
$search_ui<br />\n
$listing_text $nav_link".($_GET["_q"]=="pending"? "
<form name='payment_form' method='post' action='$this_file".($_SERVER["QUERY_STRING"]? "?$_SERVER[QUERY_STRING]" : "")."'>
<input type='hidden' name='__req' value='1' />" : "")."
<table class='aml_table' style='width:1200px;'>
	<tr class='aml_header'>
		<td><img src='".M_URL."/images/icons/edit.png'></td>".($_GET["_q"]=="pending"? "
		<td><input type='checkbox' name='pay_all' id='cpall' /></td>" : "")."
		<td>".__("ID")."</td>
		<td>".__("User")."</td>
		<td>".__("Amount")." ".__("(").$vars["currency"].__(")")."</td>
		<td>".__("Payment Type")."</td>
		<td>".__("Payee Account")."</td>
		<td>".__("Payee Name")."</td>
		<td>".__("Payee Account No.")."</td>
		<td>".__("Payment Date")."</td>
		<td>".__("Payment Reference")."</td>
		<td>".__("Remark")."</td>
		<td>".__("Status")."</td>
		<td>".__("Requested Date")."</td>
	</tr>
	$wit_row".($_GET["_q"]=="pending"? "
	<tr>
		<td colspan='13' class='padding_height center'><div style='width:600px;'>".__("When the Submit button is clicked, all the pending withdrawal records above that are checked will be marked as 'Paid', with default Payment Type being 'Cheque'.")."<br />\n<br />\n".__("Security Password").__(":")." <input type='password' name='sec_pass' /> <input type='submit' value=\"".__("Submit")."\" id='btn_sb' /> <div id='msg_box' style='margin-top:10px;'></div></div></td>
	</tr>" : "")."
</table>".($_GET["_q"]=="pending"? "
</form>" : "")."
$nav_link";
//#####END WITHDRAWAL LIST#####

$content="<h2>$page_title</h2>$wit_list";

print format_admin_page($content, $this_title, $jvscript);

function wit_search($in_get){
	global $vars, $pv;
	$db=$vars["db"];

	$get=$in_get;
	$search_type="and";
	$r_like_search=array("acc_name","acc_payee_name","acc_no");
	//format search string
	foreach($get as $field=>$value){
		$value=trim($value);
		//search checkbox option
		if(preg_match('/^_so_/', $field)){
			preg_match('/(?<=_so_).+(?=__)/', $field, $matchf);
			$f=$matchf[0];
			preg_match('/(?<=__).+$/', $field, $matchv);
			$v=$matchv[0];
			$r_searchquery[$f].=($r_searchquery[$f]? "," : "")."'$v'";
		}
		//db field name search
		if(substr($field, 0, strlen("_sp_"))=="_sp_"){
			if(strlen($value)){
				$db_fieldname=substr($field, strlen("_sp_"));
				$db_fieldname_q.=($db_fieldname_q? " and " : "")."(".(in_array($db_fieldname, $r_like_search)? format_search_field_like($db_fieldname, $value) : format_search_field($db_fieldname, $value)).")";
			}
		}
	}
	if(isset($r_searchquery)){
		foreach($r_searchquery as $field => $query){
			$option_q.=($option_q? " and " : "")."$field in ($query)";
		}
	}else{
		$option_q="1=1";
	}
	$db_fieldname_q=$db_fieldname_q? $db_fieldname_q : "1=1";

	$count_sql="select count(*) from $db->member_withdraw where $option_q and $db_fieldname_q";
	$record_sql="select * from $db->member_withdraw where $option_q and $db_fieldname_q order by id limit <%limit_start%>, <%limit%>";

	return array("count_sql"=>$count_sql, "record_sql"=>$record_sql);
}
?>